import CryptoJS, { AES, enc, mode, pad } from 'crypto-js'
// import pako, { inflate } from 'pako';
// import pako from '@/tool/SDK/pako.js'
// const pako = require('@/tool/SDK/pako.min.js')
// import {atob} from './Base64'
declare const pako: any
export class EncryptionToDecrypt {

  static keyStr = '8e61c760fc65b76a';
  static iv = '55f305bc47281b07"';

  /**
   * 加密
   * @param {string} word 加密内容
   */
  static encryptionCryptoJS(word: string) {
    const key = enc.Utf8.parse(this.keyStr),
      srcs = enc.Utf8.parse(word),
      encrypted = AES.encrypt(srcs, key, {
        iv: enc.Utf8.parse(this.iv),
        mode: mode.CBC,
        padding: pad.Pkcs7
      }),
      hexStr = encrypted.ciphertext.toString().toUpperCase();
    return hexStr.toString()
  }
  /**
   * 解密
   * @param {string} word  解密内容
   */
  static decryptionCryptoJS(word: string) {
    const key = enc.Utf8.parse(this.keyStr),
      encryptedHexStr = enc.Hex.parse(word),
      srcs = enc.Base64.stringify(encryptedHexStr),
      decrypt = AES.decrypt(srcs, key, {
        iv: enc.Utf8.parse(this.iv),
        mode: mode.CBC,
        padding: pad.Pkcs7
      });
    return enc.Utf8.stringify(decrypt).toString();
  }

  /**
   * 解压 Gzip 数据
   * @param {string} b64Data 解压
   */
  static unGzip(b64Data: string) {
    let strData = atob(b64Data),
      charData = strData.split('').map(function (x) { return x.charCodeAt(0); }),
      binData = new Uint8Array(charData),
      data = pako.inflate(binData);
    // strData = String.fromCharCode.apply(null, new  	Uint16Array(data));  
    // return decodeURIComponent(strData)（这里也可以直接return返回忽略下面步骤，但是这么做发现中文解压的时候乱码了，使用二进制转字符串的方法得以解决）
    strData = this.byteToString(data)
    return strData
  }
  /**
   * 解决中文乱码
   * @param {*} arr 
   */
  static byteToString(arr: any) {
    if (typeof arr === 'string') {
      return arr;
    }
    let str = '', _arr = arr;
    for (let i = 0; i < _arr.length; i++) {
      let one = _arr[i].toString(2),
        v = one.match(/^1+?(?=0)/);
      if (v && one.length == 8) {
        let bytesLength = v[0].length;
        let store = _arr[i].toString(2).slice(7 - bytesLength);
        for (let st = 1; st < bytesLength; st++) {
          store += _arr[st + i].toString(2).slice(2);
        }
        str += String.fromCharCode(parseInt(store, 2));
        i += bytesLength - 1;
      } else {
        str += String.fromCharCode(_arr[i]);
      }
    }
    return str;
  }
}